from BeautifulSoup import BeautifulSoup #@UnresolvedImport
import urllib2

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from google.appengine.ext import db

import calendar
import datetime
try:
    import json
except ImportError:
    import simplejson as json 

class ParseTeamTable(webapp.RequestHandler):
    def get(self):
        
        today = datetime.date.today()
        
        if(calendar.weekday(today.year, today.month, today.day) == 6):
            url = 'http://www.formula1.com/results/team/'
            req = urllib2.urlopen(url)
            page = req.read()
            soup = BeautifulSoup(page)

            table = soup.find("table", { "class" : "raceResults" })

            trs = table.findAll(name = "tr")

            for tr in trs:
                tds = tr.findAll(name = "td")
                if len(tds)>0:
                    rows = db.GqlQuery("SELECT * FROM TeamTableRow WHERE position = :1", int(tds[0].string))
                    if(rows.count(1) > 0):
                        for row in rows:
                            row.team     = str(tds[1].next.string)
                            row.points   = int(tds[2].string)
                            db.put(row)
                    else:
                        row = TeamTableRow()
                        row.position = int(tds[0].string)
                        row.team     = str(tds[1].next.string)
                        row.points   = int(tds[2].string)
                        row.put()

class TeamTableRow(db.Model):
    position = db.IntegerProperty()
    team     = db.StringProperty()
    points   = db.IntegerProperty()




class getTeamTable(webapp.RequestHandler):
    def get(self):
        rows = db.GqlQuery("SELECT * FROM TeamTableRow")
        
        l=list()
        id=0
        print 'Content-Type: text/plain'
        for row in rows:
            l.insert(id,"row")
            id=id+1
        
        
        print json.dumps(l)


application = webapp.WSGIApplication([('/set_team', ParseTeamTable), ('/get_team', getTeamTable)],debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()